//
//  XSUserAccountViewModel.swift
//  WeiDo
//
//  Created by XISHAN on 16/3/6.
//  Copyright © 2016年 XISHAN. All rights reserved.
//

import UIKit


class XSUserAccountViewModel: NSObject {
    
    var isLogin:Bool{
        
        if self.accessToken != nil && !self.isExpiresIn {
            return true
        }
        return false
    }
 
    var accessToken: String? {
        return userAccount?.access_token
    }
    
    
    //拿当前时间和过期时间作对比,过期返回true ,没过期返回false
    var isExpiresIn:Bool{
      
        
        if NSDate().compare(userAccount!.expiresDate!) == .OrderedAscending{
            return false
        }
        return true
        
    }


    var userAccount:XSUserAccount?
    
    static let sharedAccountViewModel : XSUserAccountViewModel = {
    
        let vm = XSUserAccountViewModel()
        
        vm.userAccount = vm.loadAccount()
        return vm
    }()
    
    
    //请求AccessToken
    func loadAccessToken(code:String,callBack:( isSuccess:Bool ) -> ()){
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = [
            "client_id" : OA_APPKEY,
            "client_secret":OA_APP_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": OA_redirect_uri
        ]
        
        XSNetworkTools.sharedXSNeworkTool.request(.POST, urlString: urlStr, parameters: parameters, callBack: { (responseObjc, error) -> () in
            
            if error != nil{
                print("\(error)")
                
                callBack(isSuccess: false)
            }
            print(responseObjc)
            
            let account = XSUserAccount(dict: responseObjc!)
            
            print(account)
            
            self.loadUserInformation(account,callBack:callBack )
        })
        
        
    }
    
    //发送请求获取用户信息
    private func loadUserInformation(userAccount:XSUserAccount,callBack:( isSuccess:Bool ) -> ()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        guard let accessToken = userAccount.access_token,uid = userAccount.uid else{
            print("请求参数不足")
            callBack(isSuccess: false)
            return
        }
        
        let parameters = [
            
            "access_token": accessToken,
            "uid": uid
        ]
        
        XSNetworkTools.sharedXSNeworkTool.request(.GET, urlString: urlString, parameters: parameters) { (responseObjc, error) -> () in
            
            if error != nil{
                print("个人信息请求错误")
               // SVProgressHUD.showErrorWithStatus("个人信息请求错误")
                callBack(isSuccess: false)
                return
            }
            
            print("个人信息请求成功\(responseObjc)")
            
            userAccount.screen_name = responseObjc!["screen_name"] as? String
            userAccount.avatar_large = responseObjc!["avatar_large"] as? String
            
            
            //归档
            
            self.userAccount = userAccount
            
            self.saveUserAccount(userAccount)
            // 能当前视图模型身上的模型赋值
            
            
            //回调闭包,说明登录成功
            callBack(isSuccess: true)
            
        }
    }
    // 归档与解档路径
    private let archiveFile = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")
    
    // 解档
    private func loadAccount() -> XSUserAccount? {
        return NSKeyedUnarchiver.unarchiveObjectWithFile(archiveFile) as? XSUserAccount
    }
    
    
    // 保存用户信息
    private func saveUserAccount(account: XSUserAccount) {
        NSKeyedArchiver.archiveRootObject(userAccount!, toFile: archiveFile)
    }


}


